<template>
    <div v-if="showPage" class="pa12" style="min-width: 1100px;">
        <el-card :body-style="{ padding: 0 }">
            <ul class="flex">
                <li class="pa20 border-r" style="min-width: fit-content;">
                    <div class="flex" style="min-width: 260px;">
                        <el-image :src="memberDetail.avatar" class="member-avatar"/>
                        <ul class="f-d-b f-column member-info">
                            <li class="member-info__name">{{ memberDetail.nickname || `用户${memberDetail.mobile}` }}</li>
                            <li v-if="memberDetail.level_name" class="f-c member-info__level">
                                <span class="fz10">{{ memberDetail.level_name }}</span>
                            </li>
                        </ul>
                    </div>
                    <div v-if="memberDetail.level_name && !+levelProgress.is_special" class="f-c fz12 pt10 text-nowrap">
                        <div v-if="levelProgress.currentPeriod !== '永久有效'">
                            <span>保级条件：</span>
                            <span v-if="levelProgress.point_retain > 0">需再获得 <span class="highlight-color">{{ levelProgress.point_retain }}</span> 积分</span>
                            <span v-else-if="levelProgress.cost_retain > 0">需再消费 <span class="highlight-color">{{ levelProgress.cost_retain }}</span> 元</span>
                            <span v-else>已达到保级条件</span>
                            <span class="ph10">|</span>
                        </div>
                        <span>升级条件：</span>
                        <span v-if="levelProgress.top_level">已是最高等级会员</span>
                        <span v-else-if="+levelProgress.level_up_condition === 1">今日需再获得 <span class="highlight-color">{{ levelProgress.progressNum }}</span> 积分</span>
                        <span v-else-if="+levelProgress.level_up_condition === 2">今日需再消费 <span class="highlight-color">{{ levelProgress.progressNum }}</span> 元</span>
                    </div>
                </li>
                <li class="fz12" style="width: 100%;">
                    <div class="f-c border-b" style="height: 50%;">
                        <p class="f-c" style="width: 36%;"><span class="w100 text-r">最后一次访问：</span>{{ memberDetail.last_visit_at || '--' }}</p>
                        <p class="f-c" style="width: 20%;"><span class="w80 text-r">近7天访问：</span>{{ memberDetail.last_7_visit_count || 0 }}次</p>
                        <p class="f-c" style="width: 20%;"><span class="w80 text-r">近30天访问：</span>{{ memberDetail.last_30_visit_count || 0 }}次</p>
                        <p class="f-c" style="width: 24%;"><span class="w80 text-r">近90天访问：</span>{{ memberDetail.last_90_visit_count || 0 }}次</p>
                    </div>
                    <div class="f-c" style="height: 50%;">
                        <p class="f-c" style="width: 36%;"><span class="w100 text-r">最后一次购买：</span>{{ memberDetail.last_buy_at || '--' }}</p>
                        <p class="f-c" style="width: 20%;"><span class="w80 text-r">近7天购买：</span>{{ memberDetail.last_7_buy_count || 0 }}次</p>
                        <p class="f-c" style="width: 20%;"><span class="w80 text-r">近30天购买：</span>{{ memberDetail.last_30_buy_count || 0 }}次</p>
                        <p class="f-c" style="width: 24%;"><span class="w80 text-r">近90天购买：</span>{{ memberDetail.last_90_buy_count || 0 }}次</p>
                    </div>
                </li>
            </ul>
        </el-card>

        <div class="flex mt12">
            <el-card class="fz12" style="width: 260px;min-height: 600px;">
                <p class="pb10 pt5">会员手机号：{{ memberDetail.mobile || '--' }}</p>
                <p class="pv10">会员卡号：{{ memberDetail.sn }}</p>
                <p class="pv10 f-c">
                    <span>{{ isGroupManagementPage ? '当前' : '剩余' }}积分：</span><span class="highlight-color fw600 fz14">{{ memberDetail.point || 0 }}</span>
                </p>
                <p class="pv10 f-c">
                    获取积分：<span class="highlight-color fw600 fz14">{{ memberDetail.get_point_num || 0 }}</span>
                </p>
                <p class="pv10 f-c">
                    使用积分：<span class="highlight-color fw600 fz14">{{ memberDetail.use_point_num || 0 }}</span>
                </p>
                <p class="pv10 f-c">
                    消费金额：<span class="highlight-color fw600 fz14">{{ memberDetail.cost || 0 }}</span>
                </p>
                <p class="pv10">商场入会时间：{{ memberDetail.created_at || '--' }}</p>
                <p class="pv10">微信无感积分：{{ memberDetail.wechat_quick_point == 1 ? '开通' : '未开通' }}</p>
                <p class="pv10">支付宝无感积分：{{ memberDetail.alipay_quick_point == 1 ? '开通' : '未开通' }}</p>
                <p class="pv10">真实姓名：{{ memberDetail.real_name || '--' }}</p>
                <p class="pv10">性别：{{ genderLabel[memberDetail.gender] }}</p>
                <p class="pv10">地区：
                    <span v-if="memberDetail.province || memberDetail.city">{{ memberDetail.province }}{{ memberDetail.city }}</span>
                    <span v-else>--</span>
                </p>
                <p class="pt10 pb5">会员生日：{{ memberDetail.birthday || '--' }}</p>
            </el-card>

            <div class="ml12" style="width: calc(100% - 274px);">
                <el-card :body-style="{ padding: 0 }">
                    <template #header>
                        <ul class="f-c-b">
                            <li class="f-c">
                                <span class="pr5 fz14">会员标签</span>
                                <el-tooltip content="蓝色代表手动标签；黄色代表自动标签；紫色代表系统标签" placement="top">
                                    <el-icon>
                                        <QuestionFilled/>
                                    </el-icon>
                                </el-tooltip>
                            </li>
                            <li>
                                <el-text type="primary" style="cursor: pointer;">查看更多</el-text>
                            </li>
                        </ul>
                    </template>
                    <ul v-if="memberTagList && memberTagList.length" class="flex f-warp ph24 pt24 pb12">
                        <li
                            v-for="row of memberTagList"
                            :key="row.id"
                            class="member-tag__li"
                            :class="{
                                'member-tag__manual': +row.type === memberTagManual,// 手动标签
                                'member-tag__auto': +row.type === memberTagAuto,// 自动标签
                                'member-tag__system': +row.type === memberTagSystem// 系统标签
                            }"
                        >
                            <span class="member-tag__li--name">{{ row.name }}</span>
                        </li>
                    </ul>
                    <div v-else class="text-c pa24">暂无数据</div>
                </el-card>
                <g-tabs class="pt12" v-model="tabActive" :list="tabsTable" hide-splicing>
                    <div v-if="!isGroupManagementPage" class="pb10">
                        <el-button v-if="orderActive" type="primary" :icon="Plus" @click="showDialogPayWay">新增消费记录</el-button>
                        <el-button v-if="pointActive" type="primary" :icon="Plus" @click="showDialogPoints">新增积分记录</el-button>
                    </div>
                </g-tabs>
                <div class="border-a radius-b-l-4 radius-b-r-4" style="border-top: 0;">
                    <el-table
                        v-if="orderActive"
                        :data="orderList"
                        v-loading="tableLoading"
                        :empty-text="emptyText"
                        @sort-change="tableSortChange"
                        :default-sort="defaultSort"
                        class="table-loading-mask-body"
                    >
                        <el-table-column width="150">
                            <template #header>
                                <GTableHeadSelect
                                    name="消费记录来源"
                                    :filters="payOriginFilters"
                                    v-model="tableParams[tabActive].origin"
                                    @change="mdSearch"
                                />
                            </template>
                            <template #default="{ row }">{{ row.origin }}</template>
                        </el-table-column>
                        <el-table-column label="消费金额" width="120" sortable="custom">
                            <template #default="{ row }">
                                <span v-if="row.paid_amount || row.paid_amount === 0">{{ row.paid_amount }}</span>
                                <span v-else>--</span>
                            </template>
                        </el-table-column>
                        <el-table-column width="130" show-overflow-tooltip>
                            <template #header>
                                <GTableHeadSelect
                                    name="店铺"
                                    :props="{ value: 'id', label: 'name' }"
                                    :filters="shopFilters"
                                    v-model="tableParams[tabActive].shop_id"
                                    @change="mdSearch"
                                />
                            </template>
                            <template #default="{ row }">{{ row.shop_name || '--' }}</template>
                        </el-table-column>
                        <el-table-column width="120">
                            <template #header>
                                <GTableHeadSelect
                                    name="支付方式"
                                    :filters="payWayFilters"
                                    v-model="tableParams[tabActive].pay_way"
                                    @change="mdSearch"
                                />
                            </template>
                            <template #default="{ row }">
                                <div v-if="row.pay_way">
                                    <p v-if="row.origin === '停车缴费'">
                                        <span v-if="+row.pay_type === 2">支付宝</span>
                                        <span v-else>微信</span>
                                    </p>
                                    <span v-else>{{ row.pay_way }}</span>
                                </div>
                                <span v-else>--</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="微信/支付宝/云闪付交易号" width="200" show-overflow-tooltip>
                            <template #default="{ row }">{{ row.source || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="订单号" width="150" show-overflow-tooltip>
                            <template #default="{ row }">{{ row.sn || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="消费时间" width="160" sortable="custom">
                            <template #default="{ row }">{{ row.paid_at || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="操作人" width="150" show-overflow-tooltip>
                            <template #default="{ row }">{{ row.operator || '--' }}</template>
                        </el-table-column>
                    </el-table>

                    <el-table
                        v-if="pointActive"
                        :data="pointList"
                        v-loading="tableLoading"
                        :empty-text="emptyText"
                        @sort-change="tableSortChange"
                        :default-sort="defaultSort"
                        class="table-loading-mask-body"
                    >
                        <el-table-column min-width="130" show-overflow-tooltip>
                            <template #header>
                                <GTableHeadSelect
                                    name="积分变动来源"
                                    inputSearch
                                    :filters="pointsFilters"
                                    v-model="tableParams[tabActive].origin"
                                    @change="mdSearch"
                                />
                            </template>
                            <template #default="{ row }">{{ row.origin || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="积分增加" min-width="120" property="change" sortable="custom">
                            <template #default="{ row }">
                                <span v-if="+row.type === 1">+{{ row.change }}</span>
                                <span v-else>--</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="积分扣除" min-width="120" property="type" sortable="custom">
                            <template #default="{ row }">
                                <span v-if="+row.type === 2 || +row.type === 3">-{{ row.change }}</span>
                                <span v-else>--</span>
                            </template>
                        </el-table-column>
                        <el-table-column v-if="isUniqueMemberCompany" label="商场" min-width="120" show-overflow-tooltip>
                            <template #default="{ row }">{{ row.mall_name || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="积分创建时间" min-width="160" property="created_at" sortable="custom">
                            <template #default="{ row }">{{ row.created_at || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="操作人" width="150" show-overflow-tooltip>
                            <template #default="{ row }">{{ row.operator || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="备注" min-width="180" show-overflow-tooltip>
                            <template #default="{ row }">{{ row.remark || '--' }}</template>
                        </el-table-column>
                    </el-table>

                    <el-table
                        v-if="couponActive"
                        v-loading="tableLoading"
                        :data="couponList"
                        :empty-text="emptyText"
                        @sort-change="tableSortChange"
                        :default-sort="defaultSort"
                        class="table-loading-mask-body"
                    >
                        <el-table-column label="优惠券ID" min-width="100">
                            <template #default="{ row }">{{ row.coupon_id || row.id }}</template>
                        </el-table-column>
                        <el-table-column label="优惠券名称" min-width="150" show-overflow-tooltip>
                            <template #default="{ row }">{{ row.name }}</template>
                        </el-table-column>
                        <el-table-column min-width="120">
                            <template #header>
                                <GTableHeadSelect
                                    name="优惠券类型"
                                    :filters="couponTypesFilters"
                                    v-model="tableParams[tabActive].soule"
                                    @change="mdSearch"
                                />
                            </template>
                            <template #default="{ row }">{{ couponTypesFiltersLabel[row.soule] || '--' }}</template>
                        </el-table-column>
                        <el-table-column min-width="150" label="来源" show-overflow-tooltip>
                            <template #default="{ row }">{{ row.shop_name || '--' }}</template>
                        </el-table-column>
                        <el-table-column v-if="isUniqueMemberCompany" label="商场" min-width="120" show-overflow-tooltip>
                            <template #default="{ row }">{{ row.mall_name || '--' }}</template>
                        </el-table-column>
                        <el-table-column min-width="120">
                            <template #header>
                                <GTableHeadSelect
                                    name="使用状态"
                                    :filters="userStatusFilters"
                                    v-model="tableParams[tabActive].status"
                                    @change="mdSearch"
                                />
                            </template>
                            <template #default="{ row }">{{ userStatusFiltersLabel[row.status] || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="领取时间" min-width="160" property="created_at" sortable="custom">
                            <template #default="{ row }">{{ row.created_at || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="核销时间" min-width="160">
                            <template #default="{ row }">{{ row.verified_at || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="核销店铺" min-width="150" show-overflow-tooltip>
                            <template #default="{ row }">{{ row.verified_in || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="核销人" min-width="150" show-overflow-tooltip>
                            <template #default="{ row }">{{ row.verified_by || '--' }}</template>
                        </el-table-column>
                    </el-table>

                    <el-table
                        v-if="memberActive"
                        v-loading="tableLoading"
                        :data="changeLogList"
                        :empty-text="emptyText"
                        @sort-change="tableSortChange"
                        :default-sort="defaultSort"
                        class="table-loading-mask-body"
                    >
                        <el-table-column min-width="100">
                            <template #header>
                                <GTableHeadSelect
                                    name="变动类型"
                                    :filters="changeLogFilters"
                                    v-model="tableParams[tabActive].action"
                                    @change="mdSearch"
                                />
                            </template>
                            <template #default="{ row }">{{ changeLogFiltersLabel[row.action] || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="变动内容" min-width="160" show-overflow-tooltip>
                            <template #default="{ row }">{{ row.content || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="变动时间" min-width="160" property="created_at" sortable="custom">
                            <template #default="{ row }">{{ row.created_at || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="操作人" min-width="150" property="actionName"/>
                    </el-table>

                    <div class="f-d-c pv15">
                        <GPagination
                            :current-page="tableParams[tabActive].page"
                            :page-size="tableParams[tabActive].per_page"
                            :total="tabsTable[tabActive].count"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                        />
                    </div>
                </div>
            </div>
        </div>
    </div>

    <AddPayWay v-model="dialogPayWay" :member-id="memberId"/>

    <AddPoint v-model="dialogPoints" :member-id="memberId"/>
</template>

<script setup lang="ts">
    import { reactive, ref, computed, onMounted } from "vue";
    import { ElMessage } from "element-plus";
    import { Plus, QuestionFilled } from "@element-plus/icons-vue";
    import { useRoute } from "vue-router";
    import { _mallStore } from "@/store/config";
    import { storeToRefs } from "pinia";
    import useLoading from "@/hooks/loading";

    import AddPayWay from "@/views/MemberManage/MemberList/components/AddPayWay.vue";
    import AddPoint from "@/views/MemberManage/MemberList/components/AddPoint.vue";

    import {
        getRestfulMallMemberDetail,
        getRestfulMallMemberOrders,
        postRestV3CompanyMemberDetail,
        postRestV3OrderList,
        postRestV3PointList,
        getRestfulMallMemberPoints,
        postV3LevelProgress,
        postRestV3CouponList,
        getRestfulMallMemberCoupons,
        postV3MemberChangeLog,
    } from "@/assets/api";
    import { getApiMajorListFilter, getRestfulPointsFiltersHandler } from "@/assets/api/handler";
    import { getTableSortOrder, handlerOperator, TypeSortParams, TypeTableSort } from "@/utils/handlerData";
    import { CouponTypes } from "@/filters/data";
    import { FCouponTypesLabel, FGenderLabel, FPayOriginFilters, FPayWayFilters } from "@/filters";
    import { TypeFilters } from "@/interface/filters";
    import { isMemberTagAuto, isMemberTagManual, isMemberTagSystem } from "@/utils/globalTypes";
    import { getFiltersDictLabel } from "@/filters/utils";

    const memberTagManual = ref<number>(isMemberTagManual);// 手动标签
    const memberTagAuto = ref<number>(isMemberTagAuto);// 自动标签
    const memberTagSystem = ref<number>(isMemberTagSystem);// 系统标签

    const { isUniqueMemberCompany, isGroupManagementPage } = storeToRefs(_mallStore);
    const { showLoading, hideLoading } = useLoading();
    const route = useRoute();
    const memberId: number = +route.params.id;

    const genderLabel = ref<ObjValueStr>(FGenderLabel);
    let showPage = ref<boolean>(false);
    onMounted(() => {
        getShopList();
        getPointsFilters();
        showLoading();
        getLevelProgress();
        getMemberDetail();
        getOrderList();
        getPointData();
        getCouponRecord();
        getMemberChangeLog();
    })

    let levelProgress = ref<ObjValueAny>({});
    const getLevelProgress = () => {
        postV3LevelProgress({ member_id: memberId }).then((resp: ObjValueAny) => {
            if (resp.code === 200) {
                const { data } = resp;
                if (Date.parse(data.current_period)) {
                    data.currentPeriod = data.current_period.slice(0, 10) + '到期';
                } else {
                    data.currentPeriod = data.current_period;
                }
                // level_up_condition 升级方式：0 无条件 1:积分 2消费
                if (+data.level_up_condition === 1) {
                    // 下一等级 升级条件 积分生效 0:且 1: 或
                    if (+data.point_relation === 1) {
                        data.progressNum = Math.min(+data.day_point || 999999999, +data.point || 999999999);
                    } else {
                        data.progressNum = Math.max(+data.day_point || 0, +data.point || 0);
                    }
                }
                if (+data.level_up_condition === 2) {
                    // 下一等级 升级条件 消费生效 0:且 1: 或
                    if (+data.cost_relation === 1) {
                        data.progressNum = Math.min(+data.day_cost || 999999999, +data.cost || 999999999).toFixed(2);
                    } else {
                        data.progressNum = Math.max(+data.day_cost || 0, +data.cost || 0).toFixed(2);
                    }
                }
                levelProgress.value = data;
            } else {
                ElMessage.error(resp.msg)
            }
        })
    }
    // 会员详情 ===========================================================================
    let memberDetail = ref<ObjValueAny>({});
    let memberTagList = ref<ObjValueAny[]>([]);
    const getMemberDetail = (): Promise<void> => {
        return new Promise(async resolve => {
            let resp: ObjValueAny;
            if (isGroupManagementPage.value) {
                resp = await postRestV3CompanyMemberDetail({
                    mall_id: _mallStore.mallId,
                    company_id: _mallStore.companyId,
                    member_id: memberId,
                });
            } else {
                resp = await getRestfulMallMemberDetail(memberId);
            }
            if (resp.code === 200) {
                const { data } = resp;
                if (data.real_name) {
                    data.real_name = realNameHandler(data.real_name);
                }
                memberDetail.value = data;
                if (data.label_groups) {
                    for (let row of data.label_groups) {
                        for (let ele of row.labels) {
                            memberTagList.value.push({
                                id: ele.id,
                                name: ele.name,
                                group_name: row.name,
                                type: row.type
                            })
                        }
                    }
                }
            } else {
                ElMessage.error(resp.msg);
            }
            hideLoading();
            showPage.value = true;
            resolve();
        })
    }
    const realNameHandler = (name: string) => {
        let _nameLength = name.length;
        if (_nameLength > 2) {
            return `${name.slice(0, 1)}${'*'.repeat(_nameLength - 2)}${name.slice(-1)}`;
        } else if (_nameLength === 2) {
            return `*${name.slice(-1)}`;
        }
        return name;
    }

    // 表格table切换
    const tabActive = ref<number>(0);
    const tabsTable = reactive<ObjValueAny>([
        { value: 0, label: '消费记录', count: 0 },
        { value: 1, label: '积分记录', count: 0 },
        { value: 2, label: '优惠券记录', count: 0 },
        { value: 3, label: '会员信息变动记录', count: 0 },
    ]);
    const commonParams: ObjValueAny = { page: 1, per_page: 10, order_by: '', sort: '' };
    const tableParams = reactive<{ [props: string]: ObjValueAny }>({
        // 消费记录
        0: { ...commonParams, origin: '', pay_cate: 'cash', pay_way: '', without_statuses: [16, 18], shop_id: '' },
        // 积分记录
        1: { ...commonParams, change: 2, origin: '', pay_cate: 'cash' },
        // 优惠券记录
        2: { ...commonParams, group_id: -1, soule: '', status: '' },
        // 会员信息变动记录
        3: { ...commonParams, member_id: memberId, mall_id: _mallStore.mallId, company_id: _mallStore.companyId, action: '' },
    })

    // 消费记录 ===========================================================================
    const orderActive = computed(() => {
        return tabActive.value === 0;
    })
    // 积分记录 ===========================================================================
    const pointActive = computed(() => {
        return tabActive.value === 1;
    })
    // 优惠券记录 ===========================================================================
    const couponActive = computed(() => {
        return tabActive.value === 2;
    })
    // 会员信息变动记录 ===========================================================================
    const memberActive = computed(() => {
        return tabActive.value === 3;
    })

    const mdSearch = () => {
        handleCurrentChange();
    }
    // 排序
    const defaultSort = ref<TypeTableSort>({ prop: '', order: '' });
    const tableSortChange = ({ order, prop }: TypeTableSort) => {
        const paramsSort: TypeSortParams = getTableSortOrder(order, prop);
        tableParams[tabActive.value] = Object.assign(tableParams[tabActive.value], paramsSort);
        mdSearch();
    }
    // 选择 每页条数
    const handleSizeChange = (count: number) => {
        tableParams[tabActive.value].per_page = count;
        mdSearch();
    }
    // 分页
    const handleCurrentChange = (page: number = 1) => {
        tableParams[tabActive.value].page = page;
        getTableList();
    }

    let emptyText = ref<string>('');
    let tableLoading = ref<boolean>(false);
    const getTableList = async () => {
        // 消费记录
        if (orderActive.value) {
            await getOrderList();
        }
        // 积分记录
        if (pointActive.value) {
            await getPointData();
        }
        // 优惠券记录
        if (couponActive.value) {
            await getCouponRecord();
        }
        // 会员信息变动记录
        if (memberActive.value) {
            await getMemberChangeLog();
        }
    }
    const showTableEmpty = () => {
        emptyText.value = '加载中...';
        tableLoading.value = true;
    }
    const hideTableEmpty = () => {
        emptyText.value = '暂无数据';
        tableLoading.value = false;
    }
    // 消费记录 ==============================================================================
    const payOriginFilters = reactive<TypeFilters.filter[]>(FPayOriginFilters);
    const payWayFilters = reactive<TypeFilters.filter[]>(FPayWayFilters);
    const orderList = ref<ObjValueAny[]>([]);
    const getOrderList = (): Promise<void> => {
        return new Promise(async resolve => {
            showTableEmpty();
            let resp: ObjValueAny;
            if (_mallStore.isUniqueMemberCompany) {
                resp = await postRestV3OrderList({
                    ...tableParams[0],
                    company_id: _mallStore.companyId,
                    member_id: memberId,
                    types: [1, 3, 4, 5, 6, 7, 8, 9, 11],
                }, { noRepeat: 1 });
            } else {
                resp = await getRestfulMallMemberOrders(memberId, tableParams[0], { noRepeat: 1 });
            }
            if (resp.code === 200) {
                const { data } = resp;
                for (let row of data) {
                    row.operator = handlerOperator(row.operator);
                    row.source = +row.type === 1 ? row.transaction_source : row.transaction_id;
                    if (+_mallStore.mallId === +row.shop_id) {
                        row.shop_name = '商场';
                    }
                }
                orderList.value = data;
                tabsTable[0].count = resp.meta?.total;
            } else {
                ElMessage.error(resp.msg);
            }
            hideTableEmpty();
            resolve();
        })
    }

    // 积分记录 ==============================================================================
    const pointList = ref<ObjValueAny[]>([]);
    const getPointData = (): Promise<void> => {
        return new Promise(async resolve => {
            showTableEmpty();
            let resp: ObjValueAny;
            if (isGroupManagementPage.value) {
                resp = await postRestV3PointList({
                    ...tableParams[1],
                    company_id: _mallStore.companyId,
                    member_id: memberId,
                }, { noRepeat: 2 });
            } else {
                resp = await getRestfulMallMemberPoints(memberId, tableParams[1], { noRepeat: 2 });
            }
            if (resp.code === 200) {
                const { data } = resp;
                for (let row of data) {
                    row.operator = handlerOperator(row.operator);
                    if (row.mall && row.mall.name) {
                        row.mall_name = row.mall.name;
                    }
                }
                pointList.value = data;
                tabsTable[1].count = resp.meta?.total;
            } else {
                ElMessage.error(resp.msg);
            }
            hideTableEmpty();
            resolve();
        })
    }

    // 新增 消费记录/积分记录 ===========================================================================
    let addNewType = ref<string>('');
    let dialogPayWay = ref<boolean>(false);
    let dialogPoints = ref<boolean>(false);
    // 新增消费记录
    const showDialogPayWay = () => {
        addNewType.value = 'payWay';
        dialogPayWay.value = true;
    }
    // 新增积分记录
    const showDialogPoints = () => {
        addNewType.value = 'point';
        dialogPoints.value = true;
    }

    // 店铺 筛选
    const shopFilters = ref<ObjValueAny[]>([]);
    const getShopList = async () => {
        shopFilters.value = await getApiMajorListFilter();
    }
    // 积分变动来源 筛选
    const pointsFilters = ref<ObjValueAny[]>([]);
    const getPointsFilters = async () => {
        pointsFilters.value = await getRestfulPointsFiltersHandler();
    }
    // 优惠券记录 =================================================================================
    // 使用状态
    const userStatusFilters = reactive<TypeFilters.filter[]>([
        { label: '已领取', value: 0 },
        { label: '已核销', value: 1 },
        { label: '已失效', value: 2 },
    ]);
    const userStatusFiltersLabel = reactive<ObjValueStr>(getFiltersDictLabel(userStatusFilters));
    const couponTypesFilters = reactive<TypeFilters.filter[]>(CouponTypes());
    const couponTypesFiltersLabel = reactive<ObjValueStr>(FCouponTypesLabel);
    const couponList = ref<ObjValueAny[]>([]);
    const getCouponRecord = (): Promise<void> => {
        return new Promise(async resolve => {
            showTableEmpty();
            let resp: ObjValueAny;
            if (isGroupManagementPage.value) {
                resp = await postRestV3CouponList({
                    ...tableParams[2],
                    company_id: _mallStore.companyId,
                    member_id: memberId,
                }, { noRepeat: 3 });
            } else {
                resp = await getRestfulMallMemberCoupons(memberId, tableParams[2], { noRepeat: 3 });
            }
            if (resp.code === 200) {
                const { data } = resp;
                for (let row of data) {
                    // 领取来源
                    if (row.origin === 1) {
                        row.shop_name = '商场'
                    } else if (row.origin) {
                        if (row.shop && row.shop.name) {
                            row.shop_name = row.shop.name
                        }
                    }
                    // 核销店铺
                    if (row.verified_in_shop && !row.verified_in) {
                        row.verified_in = row.verified_in_shop.name;
                    }
                    // 核销人
                    if (isGroupManagementPage.value) {
                        if (row.verified_by_user && row.verified_by_user.id) {
                            row.verified_by = handlerOperator(row.verified_by_user);
                        } else {
                            row.verified_by = '--';
                        }
                    }
                }
                couponList.value = data;
                tabsTable[2].count = resp.meta?.total;
            } else {
                ElMessage.error(resp.msg);
            }
            hideTableEmpty();
            resolve();
        })
    }
    // 会员信息变动记录 ===========================================================================
    // 变动类型
    const changeLogFilters = reactive<TypeFilters.filter[]>([
        { label: '创建用户', value: 0 },
        { label: '真实姓名', value: 1 },
        { label: '会员等级', value: 2 },
        { label: '会员性别', value: 3 },
        { label: '会员生日', value: 4 },
        { label: '所在地区', value: 5 },
        { label: '会员昵称', value: 6 }
    ]);
    const changeLogFiltersLabel = reactive<ObjValueStr>(getFiltersDictLabel(changeLogFilters));
    const changeLogList = ref<ObjValueAny[]>([]);
    const getMemberChangeLog = (): Promise<void> => {
        return new Promise(resolve => {
            showTableEmpty();
            postV3MemberChangeLog(tableParams[3], { noRepeat: 3 }).then((resp: ObjValueAny) => {
                if (resp.code === 200) {
                    const { data } = resp;
                    for (let row of data) {
                        // 变动内容
                        let content: string = '';
                        const _text = row.publish_level_gifts ? '并' : '未';
                        if (row.action === 0 && row.source === 1) {
                            content = `创建用户,${_text}赠送等级礼`;
                        } else if (row.action === 0 && row.source === 2) {
                            content = '会员注册';
                        } else if (row.action === 2 && row.source === 1) {
                            content = `由“${row.origin}”修改为“${row.attribute}”${_text}赠送了等级礼`;
                        } else if (row.action === 2 && (row.source === 2 || row.source === 3)) {
                            if (row.level_change === 1) {
                                content = `由“${row.origin}”自动升级为“${row.attribute}”`
                            } else if (row.level_change === 2) {
                                content = `由“${row.origin}”自动降级为“${row.attribute}”`
                            }
                        } else {
                            content = `由“${row.origin}”修改为“${row.attribute}”`
                        }
                        row.content = content;
                        // 操作人
                        row.actionName = '';
                        if (row.operator && row.operator.string) {
                            row.actionName = row.operator.string;
                        } else if (row.source === 3) {
                            row.actionName = '系统';
                        } else if (row.source === 2) {
                            if (row.action !== 0 && row.action !== 2) {
                                row.actionName = `${memberDetail.value.nickname}${memberDetail.value.mobile}`;
                            } else {
                                row.actionName = '系统';
                            }
                        }
                    }
                    changeLogList.value = data;
                    tabsTable[3].count = resp.meta?.total;
                } else {
                    ElMessage.error(resp.msg);
                }
                hideTableEmpty();
                resolve();
            })
        })
    }
</script>

<style scoped lang="scss">
    :deep(.el-card) {
        background-color: transparent;
    }

    .member-avatar {
        width: 54px;
        height: 54px;
        border-radius: 50%;
    }

    .member-info {
        height: 54px;
        margin-left: 12px;
        padding: 2px 0;
        box-sizing: border-box;

        &__name {
            color: $highlight-color;
            font-size: 18px;
            font-weight: 600;
        }

        &__level {
            width: fit-content;
            padding: 0 12px;
            color: $highlight-color;
            border: 1px solid;
            border-radius: 10px;
            line-height: 20px;
        }
    }

    /* 标签 */
    .member-tag__li {
        display: flex;
        align-items: center;
        height: 25px;
        padding: 1px;
        font-size: 12px;
        margin: 0 12px 12px 0;

        &--name {
            width: 100%;
            height: 100%;
            line-height: 25px;
            padding: 0 16px;
        }
    }

    /* 手动标签 */
    .member-tag__manual {
        background: linear-gradient(315deg, transparent 6px, #2BAACA 0);

        .member-tag__li--name {
            background: linear-gradient(315deg, transparent 6px, #0A2F61 0);
            color: #0DFDF2;
        }
    }

    /* 自动标签 */
    .member-tag__auto {
        background: linear-gradient(315deg, transparent 6px, #FF8D8D 0);

        .member-tag__li--name {
            background: linear-gradient(315deg, transparent 6px, #2E1111 0);
            color: #FFBBBB;
        }
    }

    /* 系统标签 */
    .member-tag__system {
        background: linear-gradient(315deg, transparent 6px, #8E5FFF 0);

        .member-tag__li--name {
            background: linear-gradient(315deg, transparent 6px, #26105B 0);
            color: #C8B2FF;
        }
    }
</style>